﻿package jakey.SalaryCount;

import jakey.SalaryCount.SQLite.dbHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class HomeActivity extends ListActivity {
    /** Called when the activity is first created. */
	public static HomeActivity self;
	private List<HashMap<String, Object>> list;
	public MyAdaptet listAdaptet;
	private int pos;
	private int curPos;
	private String curUser;
	private dbHelper db;
	private static int init = 1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.home);
        TextView titleTextView = (TextView) findViewById(R.id.title);
        titleTextView.setText(R.string.listTitle);
        
        this.db = new dbHelper(this, "salaryCount_db", null);
		self = this;
    }
    
    //取得列表数据
    private List<HashMap<String, Object>> getData() {
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        Cursor cursor = db.select("user", null, null, null, null, null, null);
        while(cursor.moveToNext()) {
        	HashMap<String, Object> map = new HashMap<String, Object>();
        	String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
        	map.put("user_name", user_name);
        	list.add(map);
        }
        cursor.close();
        return list;
    }
    
    //点击列表项触发的逻辑
	protected void onListItemClick(ListView lv, View v, int position,long id){
    	super.onListItemClick(lv, v, position, id);
    	Intent intent = new Intent();
    	HashMap<String, Object> map = list.get(position);
    	String user_name = map.get("user_name").toString();
    	intent.putExtra("user_name", user_name);
    	intent.setClass(HomeActivity.this, CountSalaryActivity.class);
//    	intent.setClass(HomeActivity.this, PersonInfoActivity.class);
    	HomeActivity.this.startActivity(intent);
    }
	
    @Override
    //当前Activity被激活时触发的逻辑
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		list = getData();
        if(list.isEmpty()) {
        	showWelcome();
        }else{
    		this.listAdaptet = new MyAdaptet(this);
    		setListAdapter(listAdaptet);
    		if(init == 1){
            	TextView titleTextView = (TextView) findViewById(R.id.title);
            	TextView tv_welcomeInfo = (TextView) findViewById(R.id.welcomeInfo);
    			titleTextView.setText("员工列表");
    			tv_welcomeInfo.setVisibility(View.GONE);
    	    	LinearLayout layout = (LinearLayout)findViewById(R.id.listLinearLayout);
    	    	layout.setVisibility(View.VISIBLE);
    			init = 0;
    		}
        }
        db.close();
	}

	//添加员工按钮的监听器
	class addButtonListener implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(HomeActivity.this, AddTeacherActivity.class);
			HomeActivity.this.startActivity(intent);
		}
    	
    }
    
    //显示欢迎信息
    public void showWelcome() {
    	TextView tv_welcomeInfo = (TextView) findViewById(R.id.welcomeInfo);
    	tv_welcomeInfo.setText("欢迎使用J^_^Q工资计算器，请添加员工信息！");
    	tv_welcomeInfo.setVisibility(View.VISIBLE);
    	TextView titleTextView = (TextView) findViewById(R.id.title);
    	titleTextView.setText("欢迎使用");
    	LinearLayout layout = (LinearLayout)findViewById(R.id.listLinearLayout);
    	layout.setVisibility(View.GONE);
    	init = 1;
    }

	@Override
	//菜单
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, 1, "退出");
		menu.add(0, 2, 2, "最小化");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	//点击菜单项触发的逻辑
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getItemId() == 1) {
			HomeActivity.this.finish();
		}else if(item.getItemId() == 2) {
			goHome(HomeActivity.this);
		}
		return super.onOptionsItemSelected(item);
	}

	//最小化
	public static void goHome(Activity activity){
		Intent intent = new Intent();
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.HOME");
		activity.startActivity(intent);
	}
	
	//采用ViewHolder模式优化listView
    public final class ViewHolder{
        public TextView user_name;
        public ImageView imgView;
    }
	
    //自定义适配器，适配textView和button同时存在的listView
	public class MyAdaptet extends BaseAdapter {
		private LayoutInflater mInflater;
		
		public MyAdaptet(Context context){
			this.mInflater = LayoutInflater.from(context);
		}
		
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			pos = position;
			// TODO Auto-generated method stub
			ViewHolder holder = null;
            if (convertView == null) {               
                holder = new ViewHolder();              
                convertView = mInflater.inflate(R.layout.user, null);
                holder.user_name = (TextView)convertView.findViewById(R.id.user_name);
                holder.imgView = (ImageView)convertView.findViewById(R.id.moreInfo_btn);
//                holder.imgView.setImageResource(R.drawable.round_arrow_right);
                convertView.setTag(holder);
                 
            }else {               
                holder = (ViewHolder)convertView.getTag();
            }           
            String user_name = (String)list.get(position).get("user_name"); 
            holder.user_name.setText(user_name);            
            holder.imgView.setOnClickListener(
            	
            	new View.OnClickListener() {
            		private int curPos = pos; 
            		public void onClick(View v) {
//            			confirmDel();
            			showMsg(curPos);
            		}
            });        
            return convertView;
		}
	}
	
	//删除
	public void confirmDel(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("J^_^Q提醒您：确认删除吗？")
			.setCancelable(false)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				//删除一项
				public void onClick(DialogInterface dialog, int id) {
					// TODO Auto-generated method stub
					HashMap<String, Object> map = list.get(curPos);					
					String user_name = map.get("user_name").toString();
					list.remove(curPos);					
					//删除数据库中数据
					int res = db.delete("user_name=?",new String[]{user_name});
					if(res >= 1){
						listAdaptet.notifyDataSetChanged();
					}
					if(list.isEmpty()) {
						showWelcome();
					}
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				//取消删除
				public void onClick(DialogInterface dialog, int id) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
		AlertDialog alert = builder.create();
		alert.show();  
	}

	class BaseDataBtnListener implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(HomeActivity.this, BaseDataActivity.class);
			HomeActivity.this.startActivity(intent);
		}
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(db != null) {
			db.close();
		}
	}
	
	public void showMsg(int pos) {
		curPos = pos;
		HashMap<String, Object> map = list.get(pos);
		curUser = map.get("user_name").toString();
		final CharSequence[] items = {"查看", "编辑", "删除"};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(curUser);
		builder.setItems(items, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
	    		Intent intent = new Intent();
	    		intent.putExtra("user_name", curUser);
		    	if(item == 0) {
		    		intent.setClass(HomeActivity.this, PersonInfoActivity.class);
		    		HomeActivity.this.startActivity(intent);
		    	} else if(item == 1){
		    		intent.setClass(HomeActivity.this, PersonInfoEditActivity.class);
		    		HomeActivity.this.startActivity(intent);
		    	} else {
		    		confirmDel();
		    	}	    	
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public void refreshListData() {
		list = getData();
    	if(this.listAdaptet == null) {
    		this.listAdaptet = new MyAdaptet(this);
    	}
    	listAdaptet.notifyDataSetChanged();
	}
	
}